<template>
  <div class="p16">
    <van-cell-group inset>
      <van-cell title="周汇总" />
      <van-field v-model="weekStart" label="周起始" placeholder="选择日期" readonly clickable @click="showDate=true" />
      <van-popup v-model:show="showDate" round position="bottom">
        <van-date-picker
          v-model="pickerDate"
          @confirm="onPickDate"
          @cancel="showDate=false"
        />
      </van-popup>
      <div style="margin: 12px 16px 0 16px">
        <van-button round block type="primary" @click="load">刷新</van-button>
      </div>
      <van-grid :border="false" :column-num="2" style="margin-top: 8px">
        <van-grid-item v-for="(v,i) in days" :key="i" @click="toggleDayDetails(i)">
          <div>周{{ i+1 }}</div>
          <van-tag :type="selectedDayIndex === i ? 'success' : 'primary'">{{ v }}</van-tag>
        </van-grid-item>
      </van-grid>
      <van-cell title="本周合计" :value="String(total)" />

      <!-- 每日明细展示区域 -->
      <van-collapse v-model="activeCollapse" accordion>
        <van-collapse-item :name="1" v-if="selectedDayIndex !== null">
          <template #title>
            <span style="font-weight: 600;">📋 周{{ selectedDayIndex + 1 }} 明细 ({{ currentDayDate }})</span>
          </template>
          <div v-if="loadingDetails" style="text-align: center; padding: 20px;">
            <van-loading type="spinner" />
          </div>
          <div v-else-if="dailyDetails" style="padding: 8px;">
            <!-- 赚取积分 -->
            <div v-if="dailyDetails.activities.length > 0" style="margin-bottom: 16px;">
              <div style="font-weight: 600; margin-bottom: 8px; color: #07c160;">🎯 赚取积分</div>
              <div v-for="activity in dailyDetails.activities" :key="activity.id"
                   style="background: #f7f8fa; padding: 8px 12px; margin-bottom: 4px; border-radius: 4px; font-size: 13px;">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                  <span>{{ activity.templateTitle }}</span>
                  <van-tag type="success">+{{ activity.points }}</van-tag>
                </div>
                <div v-if="activity.quantity > 1" style="font-size: 12px; color: #969799; margin-top: 4px;">
                  数量: {{ activity.quantity }}
                </div>
                <div v-if="activity.note" style="font-size: 12px; color: #969799; margin-top: 4px;">
                  备注: {{ activity.note }}
                </div>
                <div style="font-size: 11px; color: #c8c9cc; margin-top: 4px;">
                  {{ formatTime(activity.createdAt) }}
                </div>
              </div>
            </div>

            <!-- 兑换记录 -->
            <div v-if="dailyDetails.redemptions.length > 0" style="margin-bottom: 16px;">
              <div style="font-weight: 600; margin-bottom: 8px; color: #ee0a24;">🎁 兑换记录</div>
              <div v-for="redemption in dailyDetails.redemptions" :key="redemption.id"
                   style="background: #f7f8fa; padding: 8px 12px; margin-bottom: 4px; border-radius: 4px; font-size: 13px;">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                  <span>{{ redemption.rewardTitle }}</span>
                  <van-tag type="danger">-{{ redemption.pointsCost }}</van-tag>
                </div>
                <div v-if="redemption.note" style="font-size: 12px; color: #969799; margin-top: 4px;">
                  备注: {{ redemption.note }}
                </div>
                <div style="font-size: 11px; color: #c8c9cc; margin-top: 4px;">
                  {{ formatTime(redemption.createdAt) }}
                </div>
              </div>
            </div>

            <!-- 无记录提示 -->
            <div v-if="dailyDetails.activities.length === 0 && dailyDetails.redemptions.length === 0"
                 style="text-align: center; padding: 20px; color: #969799;">
              当天暂无记录
            </div>

            <!-- 当天统计 -->
            <div style="background: #f0f9ff; padding: 12px; border-radius: 4px; border-left: 3px solid #1989fa;">
              <div style="font-weight: 600; margin-bottom: 8px;">📊 当天汇总</div>
              <div style="display: flex; justify-content: space-between; font-size: 13px; margin-bottom: 4px;">
                <span>赚取:</span>
                <span style="color: #07c160; font-weight: 600;">+{{ dailyDetails.totalEarned }}</span>
              </div>
              <div style="display: flex; justify-content: space-between; font-size: 13px; margin-bottom: 4px;">
                <span>消费:</span>
                <span style="color: #ee0a24; font-weight: 600;">-{{ dailyDetails.totalSpent }}</span>
              </div>
              <div style="display: flex; justify-content: space-between; font-size: 14px; font-weight: 600; padding-top: 8px; border-top: 1px solid #d8e3f0;">
                <span>净值:</span>
                <span :style="{ color: dailyDetails.netPoints >= 0 ? '#07c160' : '#ee0a24' }">
                  {{ dailyDetails.netPoints >= 0 ? '+' : '' }}{{ dailyDetails.netPoints }}
                </span>
              </div>
            </div>
          </div>
        </van-collapse-item>
      </van-collapse>
    </van-cell-group>

    <van-cell-group inset style="margin-top: 16px">
      <van-cell title="积分兑换" />
      <van-field v-model="rewardTitle" label="奖励" placeholder="选择奖励" readonly clickable @click="showReward=true" />
      <van-popup v-model:show="showReward" round position="bottom">
        <van-picker :columns="rewardColumns" @confirm="onPickReward" @cancel="showReward=false" />
      </van-popup>
      <div style="margin: 12px 16px 0 16px">
        <van-button round block type="primary" @click="redeem">兑换</van-button>
      </div>
      <van-cell title="当前余额" :value="String(balance)" />
    </van-cell-group>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { showToast, showFailToast } from 'vant'
import { useChildrenStore } from '@/stores/children'
import dayjs from 'dayjs'
import timezone from 'dayjs/plugin/timezone'
import utc from 'dayjs/plugin/utc'

dayjs.extend(utc)
dayjs.extend(timezone)

// 获取本周周一的日期
function getMondayOfCurrentWeek(): string {
  const today = dayjs().tz('Asia/Shanghai')
  const dayOfWeek = today.day() // 0=周日, 1=周一, ..., 6=周六
  const daysToMonday = dayOfWeek === 0 ? -6 : 1 - dayOfWeek // 如果是周日，减6天；否则计算到周一的天数
  return today.add(daysToMonday, 'day').format('YYYY-MM-DD')
}

const children = useChildrenStore()
// 使用本周周一作为初始日期
const weekStart = ref(getMondayOfCurrentWeek())
const days = ref<number[]>([])
const total = ref(0)
const rewardTemplates = ref<any[]>([])
const selectedRewardId = ref(0)
const balance = ref(0)
const showDate = ref(false)
const showReward = ref(false)
const rewardTitle = ref('')
const rewardColumns = ref<any[]>([])

// 日期选择器的值（需要是数组格式 [year, month, day]）
const pickerDate = ref<string[]>([])

// 每日明细相关状态
const selectedDayIndex = ref<number | null>(null)
const dailyDetails = ref<any>(null)
const loadingDetails = ref(false)
const activeCollapse = ref<number[]>([])

// 计算当前选中日期
const currentDayDate = computed(() => {
  if (selectedDayIndex.value === null) return ''
  const baseDate = dayjs(weekStart.value)
  const targetDate = baseDate.add(selectedDayIndex.value, 'day')
  return targetDate.format('YYYY-MM-DD')
})

// 初始化日期选择器的值
function initPickerDate() {
  const [year, month, day] = weekStart.value.split('-')
  pickerDate.value = [year, month, day]
}

onMounted(async () => {
  initPickerDate()  // 初始化日期选择器
  await children.load()
  await loadRewards()
  await load()
  await loadBalance()
})

// 监听日期选择器的显示，每次打开时都重置为当前weekStart
watch(showDate, (newVal) => {
  if (newVal) {
    initPickerDate()
  }
})

async function loadRewards() {
  const r = await $fetch('/api/rewards/templates')
  rewardTemplates.value = r.templates
  rewardColumns.value = r.templates.map((t: any) => ({ text: `${t.title} (${t.costPoints})`, value: t.id }))
}

async function load() {
  if (!children.currentChildId) return
  const res = await $fetch('/api/summary/weekly', { params: { childId: children.currentChildId, weekStart: weekStart.value } })
  days.value = res.days
  total.value = res.total
}

async function loadBalance() {
  if (!children.currentChildId) return
  const res = await $fetch('/api/summary/balance', { params: { childId: children.currentChildId } })
  balance.value = res.balance
}

async function redeem() {
  if (!children.currentChildId || !selectedRewardId.value) return
  try {
    // 使用当前日期进行兑换，而不是 weekStart
    const today = dayjs().tz('Asia/Shanghai').format('YYYY-MM-DD')
    await $fetch('/api/redemptions', { method: 'POST', body: { childId: children.currentChildId, rewardTemplateId: selectedRewardId.value, date: today } })
    await load()
    await loadBalance()
    selectedRewardId.value = 0
    rewardTitle.value = ''
    showToast('兑换成功')
  } catch (e: any) {
    showFailToast(e?.data?.statusMessage || '兑换失败')
  }
}

function onPickDate({ selectedValues }: any) {
  const [y, m, d] = selectedValues
  const selectedDate = `${y}-${String(m).padStart(2,'0')}-${String(d).padStart(2,'0')}`

  // 计算选中日期所在周的周一
  const selected = dayjs(selectedDate).tz('Asia/Shanghai')
  const dayOfWeek = selected.day()
  const daysToMonday = dayOfWeek === 0 ? -6 : 1 - dayOfWeek
  const monday = selected.add(daysToMonday, 'day').format('YYYY-MM-DD')

  weekStart.value = monday
  showDate.value = false
  load()  // 自动加载新周的数据
}

function onPickReward({ selectedOptions }: any) {
  const opt = selectedOptions?.[0]
  if (opt) {
    selectedRewardId.value = opt.value
    rewardTitle.value = opt.text
  }
  showReward.value = false
}

// 切换某一天的明细展示
async function toggleDayDetails(dayIndex: number) {
  if (selectedDayIndex.value === dayIndex) {
    // 如果点击的是已展开的天，则折叠
    selectedDayIndex.value = null
    activeCollapse.value = []
    dailyDetails.value = null
  } else {
    // 展开新的天
    selectedDayIndex.value = dayIndex
    activeCollapse.value = [1]
    await loadDailyDetails(dayIndex)
  }
}

// 加载某一天的明细数据
async function loadDailyDetails(dayIndex: number) {
  if (!children.currentChildId) return

  loadingDetails.value = true
  dailyDetails.value = null

  try {
    const baseDate = dayjs(weekStart.value)
    const targetDate = baseDate.add(dayIndex, 'day').format('YYYY-MM-DD')

    const res = await $fetch('/api/summary/daily-details', {
      params: {
        childId: children.currentChildId,
        date: targetDate
      }
    })

    dailyDetails.value = res
  } catch (e: any) {
    showFailToast(e?.data?.statusMessage || '加载明细失败')
    selectedDayIndex.value = null
    activeCollapse.value = []
  } finally {
    loadingDetails.value = false
  }
}

// 格式化时间显示
function formatTime(dateStr: string) {
  return dayjs(dateStr).format('HH:mm:ss')
}
</script>

<style scoped>
/* 网格项点击效果 */
:deep(.van-grid-item__content) {
  cursor: pointer;
  transition: all 0.3s ease;
}

:deep(.van-grid-item__content:hover) {
  background-color: #f7f8fa;
  transform: scale(1.05);
}

:deep(.van-grid-item__content:active) {
  transform: scale(0.95);
}

/* 折叠面板动画 */
:deep(.van-collapse-item__content) {
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    max-height: 0;
  }
  to {
    opacity: 1;
    max-height: 1000px;
  }
}

/* 明细卡片悬停效果 */
.activity-card,
.redemption-card {
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.activity-card:hover,
.redemption-card:hover {
  transform: translateX(4px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}
</style>



